import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

/**
 * browser uploaded
 */
public class RegisterPerson extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String login = request.getParameter("login");
        String password = request.getParameter("password");
        PersonData person = new PersonData();
        List<PersonData> list = new ArrayList<PersonData>();

        try {

            SessionFactory sessionFactory =  new AnnotationConfiguration().configure().buildSessionFactory();
            Session session = sessionFactory.openSession();

            person.setLogin(login);
            person.setPassword(MD5(password));
            session.beginTransaction();
            session.save(person);
            session.getTransaction().commit();
            session.close();
            sessionFactory.close();

            out.println( "<h3>[" + login + "] has been registered successfully!</h3>");
            out.println(MD5(password));
        }
        catch(Exception ex) {
            out.println("<h3>[" + login + "] could NOT be registered!</h3>");
            System.out.println(ex.getMessage());
        }

        AnnotationConfiguration config = new AnnotationConfiguration();
        config.addAnnotatedClass(PersonData.class);
        SessionFactory factory= config.configure().buildSessionFactory();
        Session session = factory.getCurrentSession();
        session.beginTransaction();
        Query queryResult = session.createQuery("from PersonData");
        java.util.List allUsers;
        allUsers = queryResult.list();
        out.print("<table border =1>");
        for (int i = 0; i < allUsers.size(); i++) {
            PersonData persondata = (PersonData) allUsers.get(i);
            out.println(" <tr> <td> "+ persondata.getId()+ "</td> <td> " + persondata.getLogin()+"</td> <td>"+ persondata.getPassword()+ "</td> </tr>" );
        }
        out.print("</table>");



    }

    private String MD5(String md5) throws NoSuchAlgorithmException {

        java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
        byte[] array = md.digest(md5.getBytes());
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < array.length; ++i) {
            sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1,3));
        }

        return sb.toString();
    }


}